import 'package:flutter/material.dart';
import 'package:getx_scaffold/getx_scaffold.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import '../../../common/styles/theme_manager.dart';
import '../../../core/repository/default_api.dart';
import '../../../services/device_sn_manager.dart';
import 'manual_measure_view.dart';
import 'dart:developer' as developer;

/// 测量详情数据模型
class MeasureDetailData {
  final int value;
  final String time;
  final String date;
  final String weekName;
  final String? unit;
  final String? description;
  final Map<String, dynamic>? extraData;

  MeasureDetailData({
    required this.value,
    required this.time,
    required this.date,
    required this.weekName,
    this.unit,
    this.description,
    this.extraData,
  });

  factory MeasureDetailData.fromJson(
      Map<String, dynamic> json, MeasureType type) {
    int value = json['generalValue'] as int? ?? 0;
    String? unit;
    String? description;
    Map<String, dynamic>? extraData;

    switch (type) {
      case MeasureType.heartRate:
        unit = 'BPM';
        break;
      case MeasureType.bloodOxygen:
        unit = '%';
        break;
      case MeasureType.pressure:
        unit = '';
        extraData = {
          'level': _getPressureLevel(value),
        };
        break;
      case MeasureType.hrv:
        unit = '毫秒';
        break;
    }

    return MeasureDetailData(
      value: value,
      time: json['endHm'] as String? ?? '',
      date: json['dailyValue'] as String? ?? '',
      weekName: json['week'] as String? ?? '',
      unit: unit,
      description: description,
      extraData: extraData,
    );
  }

  static String _getPressureLevel(int value) {
    if (value < 30) return '放松';
    if (value < 60) return '正常';
    if (value < 80) return '中等';
    return '偏高';
  }
}

/// 历史记录数据模型
class HistoryRecord {
  final int value;
  final String date;

  HistoryRecord({required this.value, required this.date});
}

/// 测量详情页面
class MeasureDetailView extends StatefulWidget {
  const MeasureDetailView({super.key});

  @override
  State<MeasureDetailView> createState() => _MeasureDetailViewState();
}

class _MeasureDetailViewState extends State<MeasureDetailView> {
  late MeasureType measureType;
  late String recordId;
  final Rx<MeasureDetailData?> detailData = Rx<MeasureDetailData?>(null);
  final RxList<HistoryRecord> historyRecords = <HistoryRecord>[].obs;
  final RxBool isLoading = false.obs;

  @override
  void initState() {
    super.initState();
    final args = Get.arguments as Map<String, dynamic>?;
    final typeStr = args?['type'] as String? ?? 'heartRate';
    recordId = args?['recordId'] as String? ?? '';

    measureType = MeasureType.values.firstWhere(
      (e) => e.name == typeStr,
      orElse: () => MeasureType.heartRate,
    );

    _fetchDetailData();
    _fetchHistoryData();
  }

  /// 获取详情数据
  Future<void> _fetchDetailData() async {
    try {
      isLoading.value = true;
      developer.log('📊 获取${_getTitle()}详情数据...', name: 'MeasureDetail');

      Map<String, dynamic>? response;

      switch (measureType) {
        case MeasureType.heartRate:
          response =
              await DefaultApi().queryHeartRateDetailGet<Map<String, dynamic>>(
            id: recordId,
            isShowErrMsg: false,
            isShowLoading: false,
          );
          break;
        case MeasureType.bloodOxygen:
          response = await DefaultApi()
              .queryBloodOxygenDetailGet<Map<String, dynamic>>(
            id: recordId,
            isShowErrMsg: false,
            isShowLoading: false,
          );
          break;
        case MeasureType.pressure:
          response =
              await DefaultApi().queryPressureDetailGet<Map<String, dynamic>>(
            id: recordId,
            isShowErrMsg: false,
            isShowLoading: false,
          );
          break;
        case MeasureType.hrv:
          response = await DefaultApi().queryHrvDetailGet<Map<String, dynamic>>(
            id: recordId,
            isShowErrMsg: false,
            isShowLoading: false,
          );
          break;
      }

      if (response != null && response['code'] == 200) {
        final data = response['data'];
        if (data != null) {
          detailData.value = MeasureDetailData.fromJson(data, measureType);
          developer.log('✅ 获取详情数据成功', name: 'MeasureDetail');
        }
      }
    } catch (e) {
      developer.log('❌ 获取详情数据失败: $e', name: 'MeasureDetail');
    } finally {
      isLoading.value = false;
    }
  }

  /// 获取历史数据（最近7条）
  Future<void> _fetchHistoryData() async {
    try {
      developer.log('📊 获取${_getTitle()}历史数据...', name: 'MeasureDetail');

      final deviceSnManager = Get.find<DeviceSnManager>();
      final deviceSn = deviceSnManager.getDeviceSn();
      final now = DateTime.now();
      final recordDate =
          '${now.year}-${now.month.toString().padLeft(2, '0')}-${now.day.toString().padLeft(2, '0')}';

      Map<String, dynamic>? response;

      switch (measureType) {
        case MeasureType.heartRate:
          response = await DefaultApi()
              .queryHeartRateSevenInfoGet<Map<String, dynamic>>(
            deviceSn: deviceSn,
            recordDate: recordDate,
            type: '3',
            isShowErrMsg: false,
            isShowLoading: false,
          );
          break;
        case MeasureType.bloodOxygen:
          response = await DefaultApi()
              .queryBloodOxygenSevenInfoGet<Map<String, dynamic>>(
            deviceSn: deviceSn,
            recordDate: recordDate,
            type: '3',
            isShowErrMsg: false,
            isShowLoading: false,
          );
          break;
        case MeasureType.pressure:
          response = await DefaultApi()
              .queryPressureSevenInfoGet<Map<String, dynamic>>(
            deviceSn: deviceSn,
            recordDate: recordDate,
            type: '3',
            isShowErrMsg: false,
            isShowLoading: false,
          );
          break;
        case MeasureType.hrv:
          response =
              await DefaultApi().queryHrvSevenInfoGet<Map<String, dynamic>>(
            deviceSn: deviceSn,
            recordDate: recordDate,
            type: '3',
            isShowErrMsg: false,
            isShowLoading: false,
          );
          break;
      }

      if (response != null && response['code'] == 200) {
        final data = response['data'];
        if (data != null && data is List) {
          final List<HistoryRecord> records = [];
          // 数据是整数数组 [65, 64, 63, 62, 61, 60, 59]
          for (int i = 0; i < data.length; i++) {
            final value = data[i] as int;
            // 生成日期标签（从今天往前推）
            final date =
                DateTime.now().subtract(Duration(days: data.length - 1 - i));
            final dateStr = '${date.month}/${date.day}';
            records.add(HistoryRecord(value: value, date: dateStr));
          }
          historyRecords.value = records;
          developer.log('✅ 获取到 ${records.length} 条历史记录', name: 'MeasureDetail');
        }
      }
    } catch (e) {
      developer.log('❌ 获取历史数据失败: $e', name: 'MeasureDetail');
    }
  }

  String _getTitle() {
    switch (measureType) {
      case MeasureType.heartRate:
        return '心率';
      case MeasureType.bloodOxygen:
        return '血氧饱和度';
      case MeasureType.pressure:
        return '压力';
      case MeasureType.hrv:
        return '心率变异性';
    }
  }

  Color _getColor() {
    switch (measureType) {
      case MeasureType.heartRate:
        return const Color(0xFFFFD700);
      case MeasureType.bloodOxygen:
        return const Color(0xFF6CA6FF);
      case MeasureType.pressure:
        return const Color(0xFFED5C2F);
      case MeasureType.hrv:
        return const Color(0xFFFF6B6B);
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: Colors.black,
      body: SafeArea(
        child: Column(
          children: [
            _buildHeader(),
            Expanded(
              child: Obx(() {
                if (isLoading.value) {
                  return Center(
                    child: CircularProgressIndicator(
                      valueColor:
                          AlwaysStoppedAnimation<Color>(Colors.grey[400]!),
                    ),
                  );
                }

                return SingleChildScrollView(
                  padding: EdgeInsets.all(16.w),
                  child: Column(
                    crossAxisAlignment: CrossAxisAlignment.start,
                    children: [
                      _buildMainValue(),
                      SizedBox(height: 24.h),
                      if (measureType == MeasureType.heartRate)
                        _buildHeartRateZones(),
                      if (measureType == MeasureType.bloodOxygen)
                        _buildBloodOxygenRange(),
                      if (measureType == MeasureType.pressure)
                        _buildPressureRange(),
                      if (measureType == MeasureType.hrv) _buildHrvInfo(),
                      SizedBox(height: 24.h),
                      _buildHistoryChart(),
                    ],
                  ),
                );
              }),
            ),
          ],
        ),
      ),
    );
  }

  Widget _buildHeader() {
    return Container(
      padding: EdgeInsets.symmetric(horizontal: 16.w, vertical: 12.h),
      decoration: BoxDecoration(
        gradient: LinearGradient(
          begin: Alignment.topRight,
          end: Alignment.bottomRight,
          colors: ThemeManager.to.backgroundGradientColors,
          stops: const [0.1, 0.3, 0.7, 1.0],
        ),
      ),
      child: Row(
        children: [
          IconButton(
            onPressed: () => Get.back(),
            icon: const Icon(Icons.arrow_back_ios, color: Colors.white),
          ),
          Expanded(
            child: Center(
              child: Text(
                _getTitle(),
                style: TextStyle(
                  fontSize: 18.sp,
                  color: Colors.white,
                  fontWeight: FontWeight.w500,
                ),
              ),
            ),
          ),
          SizedBox(width: 48.w),
        ],
      ),
    );
  }

  Widget _buildMainValue() {
    final data = detailData.value;
    if (data == null) return const SizedBox.shrink();

    return Column(
      children: [
        Text(
          measureType == MeasureType.hrv ? _getTitle() : '',
          style: TextStyle(
            fontSize: 16.sp,
            color: Colors.white,
            fontWeight: FontWeight.w500,
          ),
        ),
        if (measureType == MeasureType.hrv) SizedBox(height: 8.h),
        Row(
          mainAxisAlignment: MainAxisAlignment.center,
          crossAxisAlignment: CrossAxisAlignment.end,
          children: [
            Text(
              '${data.value}',
              style: TextStyle(
                fontSize: 80.sp,
                fontWeight: FontWeight.bold,
                color: Colors.white,
                height: 1,
              ),
            ),
            Padding(
              padding: EdgeInsets.only(bottom: 16.h, left: 8.w),
              child: Text(
                data.unit ?? '',
                style: TextStyle(
                  fontSize: 20.sp,
                  color: Colors.white,
                ),
              ),
            ),
          ],
        ),
        SizedBox(height: 8.h),
        Text(
          '${data.date}，${data.weekName}，${data.time}',
          style: TextStyle(
            fontSize: 14.sp,
            color: Colors.grey[400],
          ),
        ),
      ],
    );
  }

  Widget _buildHeartRateZones() {
    return Container(
      padding: EdgeInsets.all(16.w),
      decoration: BoxDecoration(
        color: const Color.fromRGBO(3, 0, 3, 1),
        borderRadius: BorderRadius.circular(20.r),
        border: Border.all(
          color: const Color.fromRGBO(33, 33, 33, 1),
          width: 1,
        ),
      ),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          Text(
            '关于心率数据',
            style: TextStyle(
              fontSize: 16.sp,
              color: Colors.white,
              fontWeight: FontWeight.w500,
            ),
          ),
          SizedBox(height: 16.h),
          _buildZoneBar(),
          SizedBox(height: 16.h),
          _buildZoneDescription(),
        ],
      ),
    );
  }

  Widget _buildZoneBar() {
    final zones = [
      {'label': '热身放松', 'max': 117, 'color': const Color(0xFFFFD700)},
      {'label': '脂肪燃烧', 'max': 137, 'color': const Color(0xFFFFB84D)},
      {'label': '心肺强化', 'max': 156, 'color': const Color(0xFFFF8C42)},
      {'label': '耐力强化', 'max': 176, 'color': const Color(0xFFFF6B42)},
      {'label': '无氧极限', 'max': 200, 'color': const Color(0xFFFF4757)},
    ];

    return Column(
      children: [
        Container(
          height: 40.h,
          decoration: BoxDecoration(
            borderRadius: BorderRadius.circular(20.r),
            gradient: LinearGradient(
              colors: zones.map((z) => z['color'] as Color).toList(),
            ),
          ),
          child: Stack(
            children: [
              Positioned(
                left: 20.w,
                top: 0,
                bottom: 0,
                child: Icon(
                  Icons.favorite,
                  color: Colors.white,
                  size: 20.sp,
                ),
              ),
            ],
          ),
        ),
        SizedBox(height: 8.h),
        Row(
          mainAxisAlignment: MainAxisAlignment.spaceBetween,
          children: zones.map((zone) {
            return Text(
              zone['label'] as String,
              style: TextStyle(
                fontSize: 11.sp,
                color: Colors.grey[400],
              ),
            );
          }).toList(),
        ),
        SizedBox(height: 4.h),
        Row(
          mainAxisAlignment: MainAxisAlignment.spaceBetween,
          children: zones.map((zone) {
            return Text(
              '${zone['max']}',
              style: TextStyle(
                fontSize: 11.sp,
                color: Colors.grey[400],
              ),
            );
          }).toList(),
        ),
      ],
    );
  }

  Widget _buildZoneDescription() {
    return Container(
      padding: EdgeInsets.all(12.w),
      decoration: BoxDecoration(
        color: const Color.fromRGBO(33, 33, 33, 0.3),
        borderRadius: BorderRadius.circular(12.r),
      ),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          Text(
            '心率区间',
            style: TextStyle(
              fontSize: 14.sp,
              color: const Color(0xFFFF6B6B),
              fontWeight: FontWeight.w500,
            ),
          ),
          SizedBox(height: 8.h),
          Text(
            '静息心率：正常人在安静状态下每分钟心跳次数一般为60~100次。',
            style: TextStyle(
              fontSize: 13.sp,
              color: Colors.grey[400],
              height: 1.5,
            ),
          ),
          SizedBox(height: 8.h),
          Text(
            '运动心率：运动过程中根据心率区间可以判断身体的运动状态，选择合适的心率区间才能达到较好的运动效果。',
            style: TextStyle(
              fontSize: 13.sp,
              color: Colors.grey[400],
              height: 1.5,
            ),
          ),
        ],
      ),
    );
  }

  Widget _buildBloodOxygenRange() {
    return Container(
      padding: EdgeInsets.all(16.w),
      decoration: BoxDecoration(
        color: const Color.fromRGBO(3, 0, 3, 1),
        borderRadius: BorderRadius.circular(20.r),
        border: Border.all(
          color: const Color.fromRGBO(33, 33, 33, 1),
          width: 1,
        ),
      ),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          Text(
            '了解血氧饱和度数据',
            style: TextStyle(
              fontSize: 16.sp,
              color: Colors.white,
              fontWeight: FontWeight.w500,
            ),
          ),
          SizedBox(height: 16.h),
          _buildBloodOxygenBar(),
          SizedBox(height: 16.h),
          Text(
            '血氧饱和度是血液中被氧气结合的氧合血红蛋白的容量占全部可结合的血红蛋白容量的百分比，即血液中血氧的浓度，它是呼吸循环的重要生理参数。',
            style: TextStyle(
              fontSize: 13.sp,
              color: Colors.grey[400],
              height: 1.5,
            ),
          ),
          SizedBox(height: 8.h),
          Text(
            '正常动脉血氧饱和度约为95~100%',
            style: TextStyle(
              fontSize: 13.sp,
              color: Colors.grey[400],
              height: 1.5,
            ),
          ),
          SizedBox(height: 8.h),
          Row(
            children: [
              Icon(
                Icons.info_outline,
                size: 16.sp,
                color: const Color(0xFFD4A574),
              ),
              SizedBox(width: 4.w),
              Text(
                '关于血氧数据准确性',
                style: TextStyle(
                  fontSize: 13.sp,
                  color: const Color(0xFFD4A574),
                ),
              ),
            ],
          ),
        ],
      ),
    );
  }

  Widget _buildBloodOxygenBar() {
    return Column(
      children: [
        Container(
          height: 40.h,
          decoration: BoxDecoration(
            borderRadius: BorderRadius.circular(20.r),
            gradient: const LinearGradient(
              colors: [
                Color(0xFFD4A574),
                Color(0xFFD4A574),
              ],
            ),
          ),
        ),
        SizedBox(height: 8.h),
        Row(
          mainAxisAlignment: MainAxisAlignment.spaceBetween,
          children: [
            Text('80%',
                style: TextStyle(fontSize: 12.sp, color: Colors.grey[400])),
            Text('85%',
                style: TextStyle(fontSize: 12.sp, color: Colors.grey[400])),
            Text('90%',
                style: TextStyle(fontSize: 12.sp, color: Colors.grey[400])),
            Text('95%',
                style: TextStyle(fontSize: 12.sp, color: Colors.grey[400])),
            Text('100%',
                style: TextStyle(fontSize: 12.sp, color: Colors.grey[400])),
          ],
        ),
      ],
    );
  }

  Widget _buildPressureRange() {
    final data = detailData.value;

    return Container(
      padding: EdgeInsets.all(16.w),
      decoration: BoxDecoration(
        color: const Color.fromRGBO(3, 0, 3, 1),
        borderRadius: BorderRadius.circular(20.r),
        border: Border.all(
          color: const Color.fromRGBO(33, 33, 33, 1),
          width: 1,
        ),
      ),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          _buildPressureBar(data?.value ?? 0),
        ],
      ),
    );
  }

  Widget _buildPressureBar(int value) {
    return Column(
      children: [
        Container(
          height: 40.h,
          decoration: BoxDecoration(
            borderRadius: BorderRadius.circular(20.r),
            gradient: const LinearGradient(
              colors: [
                Color(0xFFFFB84D),
                Color(0xFFFF8C42),
                Color(0xFFFF6B42),
                Color(0xFFED5C2F),
              ],
            ),
          ),
          child: Stack(
            children: [
              Positioned(
                left: (value / 100) * (1.sw - 64.w),
                top: 0,
                bottom: 0,
                child: Icon(
                  Icons.flash_on,
                  color: Colors.white,
                  size: 24.sp,
                ),
              ),
            ],
          ),
        ),
        SizedBox(height: 8.h),
        Row(
          mainAxisAlignment: MainAxisAlignment.spaceBetween,
          children: [
            Text('0',
                style: TextStyle(fontSize: 12.sp, color: Colors.grey[400])),
            Text('放松',
                style: TextStyle(fontSize: 12.sp, color: Colors.grey[400])),
            Text('30',
                style: TextStyle(fontSize: 12.sp, color: Colors.grey[400])),
            Text('正常',
                style: TextStyle(fontSize: 12.sp, color: Colors.grey[400])),
            Text('60',
                style: TextStyle(fontSize: 12.sp, color: Colors.grey[400])),
            Text('中等',
                style: TextStyle(fontSize: 12.sp, color: Colors.grey[400])),
            Text('80',
                style: TextStyle(fontSize: 12.sp, color: Colors.grey[400])),
            Text('偏高',
                style: TextStyle(fontSize: 12.sp, color: Colors.grey[400])),
            Text('100',
                style: TextStyle(fontSize: 12.sp, color: Colors.grey[400])),
          ],
        ),
      ],
    );
  }

  Widget _buildHrvInfo() {
    return Container(
      padding: EdgeInsets.all(16.w),
      decoration: BoxDecoration(
        color: const Color.fromRGBO(3, 0, 3, 1),
        borderRadius: BorderRadius.circular(20.r),
        border: Border.all(
          color: const Color.fromRGBO(33, 33, 33, 1),
          width: 1,
        ),
      ),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          Text(
            '了解心率变异性数据',
            style: TextStyle(
              fontSize: 16.sp,
              color: Colors.white,
              fontWeight: FontWeight.w500,
            ),
          ),
          SizedBox(height: 12.h),
          Text(
            '心率变异性(HRV)用于测量心跳间隔时间的差异。通过心率传感器测量到的心跳间隔之标准差来计算HRV。HRV适用于18岁以上的用户。',
            style: TextStyle(
              fontSize: 13.sp,
              color: Colors.grey[400],
              height: 1.5,
            ),
          ),
          SizedBox(height: 12.h),
          Text(
            '如果每两次心跳间隔时间的差异不大，则HRV就比较低；反之，则HRV就比较高。HRV越高越好，代表有着更加的心血管能和抗压承受能力。',
            style: TextStyle(
              fontSize: 13.sp,
              color: Colors.grey[400],
              height: 1.5,
            ),
          ),
        ],
      ),
    );
  }

  Widget _buildHistoryChart() {
    return Obx(() {
      if (historyRecords.isEmpty) {
        return const SizedBox.shrink();
      }

      return Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          Text(
            '最近7次记录',
            style: TextStyle(
              fontSize: 16.sp,
              color: Colors.white,
              fontWeight: FontWeight.w500,
            ),
          ),
          SizedBox(height: 16.h),
          _buildBarChart(),
        ],
      );
    });
  }

  Widget _buildBarChart() {
    final records = historyRecords.take(7).toList();
    if (records.isEmpty) return const SizedBox.shrink();

    final maxValue =
        records.map((r) => r.value).reduce((a, b) => a > b ? a : b).toDouble();
    final minValue =
        records.map((r) => r.value).reduce((a, b) => a < b ? a : b).toDouble();
    final range = maxValue - minValue;

    return Container(
      height: 200.h,
      padding: EdgeInsets.all(16.w),
      decoration: BoxDecoration(
        color: const Color.fromRGBO(3, 0, 3, 1),
        borderRadius: BorderRadius.circular(20.r),
        border: Border.all(
          color: const Color.fromRGBO(33, 33, 33, 1),
          width: 1,
        ),
      ),
      child: Row(
        crossAxisAlignment: CrossAxisAlignment.end,
        mainAxisAlignment: MainAxisAlignment.spaceEvenly,
        children: records.map((record) {
          // 为文本预留空间：文本高度约16.h + 间距8.h = 24.h
          final maxBarHeight = 200.h - 32.w - 24.h; // 总高度 - padding - 文本区域
          final normalizedHeight = range > 0
              ? ((record.value - minValue) / range) * (maxBarHeight - 30.h) + 30.h
              : maxBarHeight * 0.5;

          return Expanded(
            child: Padding(
              padding: EdgeInsets.symmetric(horizontal: 4.w),
              child: Column(
                mainAxisAlignment: MainAxisAlignment.end,
                mainAxisSize: MainAxisSize.min,
                children: [
                  // 柱子
                  Container(
                    width: 32.w,
                    height: normalizedHeight,
                    decoration: BoxDecoration(
                      color: _getColor(),
                      borderRadius: BorderRadius.vertical(
                        top: Radius.circular(8.r),
                      ),
                    ),
                  ),
                  SizedBox(height: 6.h),
                  // 数值显示在柱子下方
                  Text(
                    '${record.value}',
                    style: TextStyle(
                      fontSize: 11.sp,
                      color: Colors.grey[400],
                    ),
                  ),
                ],
              ),
            ),
          );
        }).toList(),
      ),
    );
  }
}
